package controllers

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"zero_six/goods/pb/goods"
	"zero_six/house/utils"

	beego "github.com/beego/beego/v2/server/web"
)

type GoodsController struct {
	beego.Controller
}

func (this *GoodsController) CreateGoods() {

	// 使用到用户ID
	//fmt.Println(this.Ctx.Input.GetData("username"), "在控制器里面获取token里面的负载数据")
	//fmt.Println(this.GetSession("username"))
	//fmt.Println("goods action")
	// 商品参数的验证。。

	goods_price, _ := this.GetFloat("goods_price")
	// 处理
	f, h, err := this.GetFile("goods_img") //接受文件上传数据
	if err != nil {
		this.Data["json"] = map[string]interface{}{
			"code": http.StatusMultiStatus,
			"msg":  "上传图片信息错误",
		}
		this.ServeJSON()
		return
	}
	defer f.Close()
	// 图片大小验证
	if h.Size > 2*1024*1024 {
		this.Data["json"] = map[string]interface{}{
			"code": http.StatusMultiStatus,
			"msg":  "上传图片过大，请更换其他图片",
		}
		this.ServeJSON()
		return
	}
	// 图片后缀的验证
	if !strings.HasSuffix(h.Filename, "png") && !strings.HasSuffix(h.Filename, "jpg") {
		this.Data["json"] = map[string]interface{}{
			"code": http.StatusMultiStatus,
			"msg":  "图片格式不正确、只允许png格式",
		}
		this.ServeJSON()
		return
	}

	goods_img := "static/img/" + h.Filename
	this.SaveToFile("goods_img", goods_img)

	client := goods.NewGoodsClient(utils.GetRpcClient("goods.rpc").Conn())
	resp, err := client.Save(context.Background(), &goods.Request{
		GoodsName:  this.GetString("goods_name"),
		GoodsPrice: float32(goods_price),
		GoodsImg:   "http://127.0.0.1:9998/" + goods_img,
		Status:     0,
		Detail:     this.GetString("detail"),
	})
	if err != nil {
		this.Data["json"] = map[string]interface{}{
			"code": http.StatusMultiStatus,
			"msg":  "添加失败",
		}
		this.ServeJSON()
		return
	}

	fmt.Println(resp)

	this.Data["json"] = map[string]interface{}{
		"code": http.StatusOK,
		"msg":  "添加成功",
	}
	this.ServeJSON()

}
